'use client';

import React, { useState, useEffect } from 'react';
import { Form, Input, Select, Tag, Button, message, Spin, Modal, Card, Pagination } from 'antd';
import { useParams, useRouter } from 'next/navigation';
import api from '../../../utils/api';
import { useUser } from '../../../context/userContext';

const { Option } = Select;

const EditPostPage = () => {
    const { postId } = useParams();
    const router = useRouter();
    const [form] = Form.useForm();
    const [loading, setLoading] = useState(true);
    const [tags, setTags] = useState<any[]>([]);
    const [selectedTags, setSelectedTags] = useState<string[]>([]);
    const [categories, setCategories] = useState<any[]>([]);
    const [selectedCategory, setSelectedCategory] = useState<string>('');
    const [deleting, setDeleting] = useState(false);
    const [deletePostConfirmVisible, setDeletePostConfirmVisible] = useState(false);
    const [page, setPage] = useState(1);
    const [pageSize, setPageSize] = useState(10);
    const [totalTags, setTotalTags] = useState(0);
    const { user } = useUser();
    const accessToken = user ? user.access_token : "";

    useEffect(() => {
        const fetchPost = async () => {
            try {
                const response = await api.get(`/posts/detail`, {
                    params: { id: postId },
                    headers: {
                        'Authorization': `Bearer ${accessToken}`
                    }
                });
                if (response.status === 200) {
                    const postData = response.data;
                    const responseCategory = await api.get(`/categories/detail`, {
                        params: { id: postData.categoryId },
                        headers: {
                            'Authorization': `Bearer ${accessToken}`
                        }
                    });
                    const categoryData = responseCategory.data.name; // category's name
                    form.setFieldsValue({
                        id: postData.id,
                        title: postData.title,
                        content: postData.content,
                        category: categoryData,
                        tags: postData.tags || []
                    });
                    setSelectedTags(postData.tagNames || []);
                    setSelectedCategory(categoryData); 
                }
            } catch (error) {
                console.error('获取帖子信息失败:', error);
                message.error('获取帖子信息失败，请稍后重试');
            } finally {
                setLoading(false);
            }
        };

        fetchPost();
    }, [postId, form, accessToken]);

    useEffect(() => {
        const fetchCategories = async () => {
            try {
                const response = await api.get('/categories/all');
                if (response.status === 200 && Array.isArray(response.data.Reponse)) {
                    setCategories(response.data.Reponse);
                } else {
                    setCategories([]);
                }
            } catch (error) {
                console.error('获取分区数据失败:', error);
                setCategories([]);
            }
        };

        fetchCategories();
    }, []);

    useEffect(() => {
        const fetchTags = async () => {
            setLoading(true);
            try {
                const response = await api.get('/tags/all', {
                    params: {
                        page: page.toString(),
                        pageSize: pageSize.toString(),
                    },
                });
                if (response.status === 200) {
                    setTags(response.data.Tags);
                    setTotalTags(response.data.total);
                } else {
                    setTags([]);
                    setTotalTags(0);
                }
            } catch (error) {
                console.error('获取标签数据失败:', error);
                setTags([]);
                setTotalTags(0);
            } finally {
                setLoading(false);
            }
        };

        fetchTags();
    }, [page, pageSize]);

    const onFinish = async (values) => {
        try {
            console.log("post content:", selectedCategory);
            const response = await api.put('/posts/update', {
                ...values,
                category: selectedCategory,
                tags: selectedTags,
            }, {
                headers: {
                    'Authorization': `Bearer ${accessToken}`
                }
            });

            if (response.status === 200) {
                message.success('帖子更新成功');
                router.back();
            }
        } catch (error) {
            console.error('更新帖子失败:', error);
            message.error('更新帖子失败，请稍后重试');
        }
    };

    const handleSelectTag = (tagName: string) => {
        if (!selectedTags.includes(tagName)) {
            setSelectedTags([...selectedTags, tagName]);
        }
    };

    const handleRemoveTag = (tag: string) => {
        setSelectedTags(selectedTags.filter(tagId => tagId !== tag));
    };

    const confirmDelete = () => {
        setDeletePostConfirmVisible(true);
    };

    const handleDeletePost = async () => {
        setDeleting(true);
        try {
            const response = await api.delete(`/posts/delete`, {
                params: { id: postId },
                headers: {
                    'Authorization': `Bearer ${accessToken}`
                }
            });
            if (response.status === 200) {
                message.success('帖子删除成功');
                setDeletePostConfirmVisible(false);
                router.push('/homepage/home');
            }
        } catch (error) {
            console.error('删除帖子失败:', error);
            message.error('删除帖子失败，请稍后重试');
        } finally {
            setDeleting(false);
        }
    };

    return (
        <div style={{
            maxWidth: '800px',
            margin: '0 auto',
            marginTop: '30px',
            padding: '24px',
            position: 'relative',
            backgroundColor: '#fefefe',
            borderRadius: '12px',
            boxShadow: '0 4px 20px rgba(0, 0, 0, 0.05)'
        }}>
            <Button
                type="primary"
                style={{ backgroundColor: '#ddd', color: 'white', fontWeight:'bold', borderRadius: '4px', border: 'none', marginBottom: '20px' }}
                onClick={() => router.back()}
            >
                返回
            </Button>
            <h1 style={{ fontSize: '28px', fontWeight: 'bold', marginTop: '10px' }}>编辑帖子</h1>
            <Form
                form={form}
                name="editPost"
                onFinish={onFinish}
                initialValues={{
                    id: null,
                    title: '',
                    content: '',
                    category: '',
                    tags: selectedTags
                }}
                scrollToFirstError
            >
                <Form.Item 
                    name="id" hidden>
                    <Input />
                </Form.Item>
                <Form.Item 
                    label="标题" 
                    name="title" 
                    rules={[{ required: true, message: '请输入帖子标题' }]}>
                    <Input />
                </Form.Item>
                <Form.Item 
                    label="内容" 
                    name="content" 
                    rules={[{ required: true, message: '请输入帖子内容' }]}>
                    <Input.TextArea rows={4} />
                </Form.Item>
                <Form.Item 
                    label="分区" 
                    name="category" 
                    rules={[{ required: true, message: '请选择分区' }]}> 
                    <Select 
                        placeholder="请选择分区" 
                        value={selectedCategory} 
                        onChange={(value) => setSelectedCategory(value)}>{
                            categories.map((category) => (
                                <Option key={category.id} value={category.name}>
                                    {category.name}
                                </Option>
                            ))
                        }
                    </Select>
                </Form.Item>
                <Form.Item label="标签" name="tags" style = {{marginLeft:'11px'}}>
                    <div>
                        <div style={{ display: 'flex', flexWrap: 'wrap', gap: '5px' , marginTop:'5px'}}>
                            {selectedTags.map((tag) => (
                                <Tag 
                                    key={tag} 
                                    closable 
                                    onClose={() => handleRemoveTag(tag)}
                                    style={{ fontSize: '14px', padding: '6px 18px' }} // 字体 & 内边距
                                >
                                    {tag + "   "} 
                                </Tag>
                            ))}
                        </div>
                        <div style={{ marginTop: '15px' , marginBottom:'10px'}}>
                            {loading ? (
                                <Spin />
                            ) : (
                                <div style={{ display: 'flex', flexWrap: 'wrap', gap: '8px' }}>
                                    {tags.map((tag) => (
                                        <Card
                                            key={tag.id}
                                            hoverable
                                            onClick={() => handleSelectTag(tag.name)}
                                            style={{ margin: 0, padding: '6px 12px', fontSize: '14px', width: 'auto', cursor: 'pointer' }}
                                            bodyStyle={{ padding: '3px 5px' }} // 控制内部间距
                                        >
                                            <span>{tag.name}</span>
                                        </Card>
                                    ))}
                                </div>
                            )}
                        </div>
                        <Pagination current={page} pageSize={pageSize} total={totalTags} onChange={(page, pageSize) => { setPage(page); setPageSize(pageSize); }} />
                    </div>
                </Form.Item>
                <Form.Item style = {{marginTop: '20px'}}>
                    <Button type="danger" onClick={confirmDelete} loading={deleting} style={{ marginRight: '10px' }}>删除帖子</Button>
                    <Button type="primary" htmlType="submit" loading={loading}>提交更新</Button>
                </Form.Item>
            </Form>
            <Modal
                title="确认删除帖子"
                open={deletePostConfirmVisible}
                onOk={handleDeletePost}
                onCancel={() => setDeletePostConfirmVisible(false)}
                okText="删除"
                cancelText="取消"
                okButtonProps={{ danger: true, loading: deleting }}
            >
                <p>您确定要删除这个帖子吗？此操作不可撤销。</p>
            </Modal>
        </div>
    );
};

export default EditPostPage;
